import { defineStore } from 'pinia'
import { computed, reactive } from 'vue'
import type { MessageType, SessionItem } from '@/services/types.ts'
import { queryPageSessionList } from '@/services/chatApi.ts'
import { useGlobalStorage } from '@/stores/global.ts'
import { queryPageMessageList } from '@/services/messageApi.ts'

/**
 * 存储房间数据
 */
// 分页大小
export const pageSize = 20
// 标识是否第一次请求
const isFirstInit = false
export const useChatStorage = defineStore('chatStorage', () => {
  //全局存储
  const globalStore = useGlobalStorage()
  //会话列表(消息列表)b
  const sessionList = reactive<SessionItem[]>([])
  //会话列表参数
  const sessionOptions = reactive({ isLast: false, isLoading: false, cursor: '' })
  //当前会话ID
  const currentSessionId = computed(() => globalStore.currentSession.roomId)
  //当前会话类别
  const currentSessionType = computed(() => globalStore.currentSession.type)
  //每个房间分页参数映射(key: 房间id，value：分页参数)
  const sessionOptionsMap = new Map<
    number,
    { isLast: boolean; isLoading: boolean; cursor: string }
  >(new Map([[currentSessionId.value, { isLast: false, isLoading: false, cursor: '' }]]))
  //房间消息映射(key: 房间id，value：消息列表Map数据存储)
  const msgMap = new Map<number, Map<number, MessageType>>(
    new Map([[currentSessionId.value, new Map<number, MessageType>()]]),
  )
  //消息列表分页参数
  const messageOptions = reactive<
    Map<number, { isLast: boolean; isLoading: boolean; cursor: string }>
  >(new Map([[currentSessionId.value, { isLast: false, isLoading: false, cursor: '' }]]))
  //获取当前消息Map(获取当前会话消息Map)
  const getMsgMap = computed({
    get() {
      const value = msgMap.get(currentSessionId.value as number)
      if (!value) {
        return new Map<number, MessageType>()
      }
      return value
    },
    set(value) {
      msgMap.set(currentSessionId.value as number, value)
    },
  })
  //获取当前会话分页参数
  const getSessionOption = computed({
    get() {
      const value = sessionOptionsMap.get(currentSessionId.value as number)
      if (!value) {
        return { isLast: false, isLoading: false, cursor: '' }
      }
      return value
    },
    set(value) {
      sessionOptionsMap.set(currentSessionId.value as number, value)
    },
  })
  //当前消息列表分页参数
  const currentMessageOptions = computed({
    get: () => {
      const current = messageOptions.get(currentSessionId.value as number)
      if (!current) {
        messageOptions.set(currentSessionId.value, { isLast: false, isLoading: true, cursor: '' })
      }
      return messageOptions.get(currentSessionId.value as number)
    },
    set: (val) => {
      messageOptions.set(
        currentSessionId.value,
        val as { isLast: boolean; isLoading: boolean; cursor: string },
      )
    },
  })

  //============================获取会话列表数据====================================
  const getSessionList = async (isFresh = false) => {
    if (isFresh && (sessionOptions.isLast || sessionOptions.isLoading)) {
      return
    }
    //请求会话数据
    const data = await queryPageSessionList({
      params: {
        pageSize: sessionList.length > pageSize ? sessionList.length : pageSize,
        cursor: isFresh || !sessionOptions.cursor ? undefined : sessionOptions.cursor,
      },
    })
      .send()
      .catch(() => {
        sessionOptions.isLoading = false
      })
    //覆值新的游标数据值
    if (!data) return
    sessionOptions.cursor = data.cursor
    sessionOptions.isLast = data.isLast

    if (isFresh) {
      //刷新数据
      sessionList.splice(0, sessionList.length, ...data.list)
    } else {
      sessionList.push(...data.list)
    }

    //第一次初始化数据
    if (!isFirstInit) {
      //设置当前会话，默认选中第一个
      globalStore.currentSession.roomId = data.list[0].id
      globalStore.currentSession.type = data.list[0].roomType
      //加载消息列表数据
      getMsgList()


    }
  }

  //=================获取聊天室消息列表数据=====================
  const getMsgList = async (size = pageSize) => {
    //=========加载=========
    if (currentMessageOptions.value) {
      currentMessageOptions.value.isLoading = true
    }

    //获取聊天数据数据列表
    const data = await queryPageMessageList({
      params: {
        pageSize: size,
        cursor: currentMessageOptions.value?.cursor,
        roomId: currentSessionId.value,
      },
    })
      .send()
      .finally(() => {
        if (currentMessageOptions.value) {
          currentMessageOptions.value.isLoading = false
        }
      })

    if (!data) return

    //清空当前消息列表
    getMsgMap.value?.clear() // 清空Map

    //放入消息列表
    const msgMap = getMsgMap.value
    data.list.forEach((mes) => {
      msgMap.set(mes.messageInfo.id, mes)
    })

    //刷新当前房间消息分页参数
    const currentOptions = currentMessageOptions.value;
    if(!currentOptions)return
    currentOptions.cursor = data.cursor
    currentOptions.isLast = data.isLast
  }

  return { sessionList, sessionOptions, getSessionList,getMsgMap }
})
